<?php
if (!file_exists('../install.lock')) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => '系统未安装']);
    exit;
}

require_once 'config.php';
require_once 'alipay.php';

// 记录调试日志
function writeDebugLog($message) {
    $log_file = __DIR__ . '/payment_debug.log';
    $time = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$time] $message\n", FILE_APPEND | LOCK_EX);
}

header('Content-Type: application/json');

$order_no = $_POST['order_no'] ?? '';

writeDebugLog("--- [START] check_payment.php for order: $order_no ---");

if (empty($order_no)) {
    writeDebugLog("[ERROR] 订单号为空");
    echo json_encode(['success' => false, 'message' => '订单号不能为空']);
    exit;
}

try {
    // 获取订单信息
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE order_no = ?");
    $stmt->execute([$order_no]);
    $order = $stmt->fetch();
    
    if (!$order) {
        writeDebugLog("[ERROR] 订单不存在: $order_no");
        echo json_encode(['success' => false, 'message' => '订单不存在']);
        exit;
    }
    writeDebugLog("订单信息获取成功: " . json_encode($order));
    
    // 如果订单已支付，直接返回
    if ($order['status'] === 'paid') {
        writeDebugLog("订单状态已为 'paid'，直接返回成功。");
        echo json_encode(['success' => true, 'status' => 'paid', 'message' => '支付成功']);
        exit;
    }
    
    // 如果订单已过期，直接返回
    if ($order['status'] === 'expired') {
        writeDebugLog("订单状态为 'expired'，直接返回。");
        echo json_encode(['success' => true, 'status' => 'expired', 'message' => '订单已过期']);
        exit;
    }
    
    // 检查订单是否超时（5分钟）
    $created_time = strtotime($order['created_at']);
    $current_time = time();
    $timeout = 5 * 60; // 5分钟
    
    if ($current_time - $created_time > $timeout) {
        writeDebugLog("订单超时，更新状态为 'expired'");
        // 更新订单状态为过期
        $stmt = $pdo->prepare("UPDATE orders SET status = 'expired' WHERE order_no = ?");
        $stmt->execute([$order_no]);
        
        echo json_encode(['success' => true, 'status' => 'expired', 'message' => '订单已过期']);
        exit;
    }
    
    // 查询支付宝订单状态
    writeDebugLog("开始查询支付宝订单状态...");
    $alipay = new AlipayF2F(
        ALIPAY_APP_ID,
        ALIPAY_PRIVATE_KEY,
        ALIPAY_PUBLIC_KEY,
        ALIPAY_NOTIFY_URL,
        ALIPAY_RETURN_URL
    );
    
    $result = $alipay->queryOrder($order_no);
    writeDebugLog("支付宝查询结果: " . json_encode($result));
    
    if ($result && isset($result['trade_status'])) {
        if ($result['trade_status'] === 'TRADE_SUCCESS') {
            writeDebugLog("支付宝返回支付成功 (TRADE_SUCCESS)。开始处理订单...");
            
            // 支付成功，更新订单状态
            $pdo->beginTransaction();
            writeDebugLog("数据库事务开始。");

            $stmt = $pdo->prepare("UPDATE orders SET status = 'paid', paid_at = NOW(), trade_no = ? WHERE order_no = ? AND status = 'pending'");
            $updateResult = $stmt->execute([$result['trade_no'], $order_no]);
            
            if ($updateResult && $stmt->rowCount() > 0) {
                writeDebugLog("订单状态更新为 'paid' 成功。");
                // 生成卡密并发送
                $kamiResult = generateAndSendKami($order, $pdo);
                if ($kamiResult) {
                    writeDebugLog("generateAndSendKami 函数成功执行。");
                    $pdo->commit();
                    writeDebugLog("数据库事务提交。");
                    echo json_encode(['success' => true, 'status' => 'paid', 'message' => '支付成功']);
                } else {
                    writeDebugLog("[ERROR] generateAndSendKami 函数执行失败，回滚事务。");
                    $pdo->rollBack();
                    echo json_encode(['success' => false, 'message' => '卡密生成失败，请联系管理员']);
                }
            } else {
                writeDebugLog("[WARNING] 订单状态更新失败或已被其他进程处理。");
                $pdo->rollBack();
                 // 可能已被notify.php处理，所以返回成功让前端跳转
                echo json_encode(['success' => true, 'status' => 'paid', 'message' => '支付已处理']);
            }
            exit;

        } elseif ($result['trade_status'] === 'TRADE_CLOSED') {
            writeDebugLog("支付宝返回交易关闭 (TRADE_CLOSED)，更新状态为 'expired'");
            // 交易关闭，更新订单状态
            $stmt = $pdo->prepare("UPDATE orders SET status = 'expired' WHERE order_no = ?");
            $stmt->execute([$order_no]);
            
            echo json_encode(['success' => true, 'status' => 'expired', 'message' => '订单已关闭']);
            exit;
        } else {
            // 其他状态，继续等待
            writeDebugLog("支付宝返回等待状态: " . $result['trade_status']);
            echo json_encode(['success' => true, 'status' => 'pending', 'message' => '等待支付']);
            exit;
        }
    } else {
        // 查询失败，返回等待状态
        writeDebugLog("[WARNING] 查询支付宝订单失败或未获取到交易状态。");
        echo json_encode(['success' => true, 'status' => 'pending', 'message' => '等待支付']);
        exit;
    }
    
} catch (Exception $e) {
    writeDebugLog("[FATAL] 脚本发生异常: " . $e->getMessage());
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
        writeDebugLog("异常发生，事务已回滚。");
    }
    echo json_encode(['success' => false, 'message' => '查询失败：' . $e->getMessage()]);
    exit;
}

/**
 * 生成卡密并发送
 */
function generateAndSendKami($order, $pdo) {
    writeDebugLog("--- [START] generateAndSendKami for order: {$order['order_no']} ---");
    
    try {
        // 获取商品信息
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$order['product_id']]);
        $product = $stmt->fetch();
        
        if (!$product) {
            writeDebugLog("[ERROR] 商品信息未找到. Product ID: {$order['product_id']}");
            return false;
        }
        writeDebugLog("商品信息获取成功: " . json_encode($product));
        
        // 生成卡密
        $kami_list = [];
        for ($i = 0; $i < $order['quantity']; $i++) {
            $kami_key = generateKamiKey();
            writeDebugLog("生成卡密 (" . ($i+1) . "/{$order['quantity']}): $kami_key");
            
            // 计算过期时间
            $expire_time = null;
            if ($product['duration_type'] && $product['duration_value'] > 0) {
                switch ($product['duration_type']) {
                    case 'minute':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} minutes"));
                        break;
                    case 'hour':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} hours"));
                        break;
                    case 'day':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} days"));
                        break;
                    case 'week':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} weeks"));
                        break;
                    case 'month':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} months"));
                        break;
                    case 'year':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} years"));
                        break;
                }
            }
            
            // 插入卡密
            $stmt_kami = $pdo->prepare("INSERT INTO kami (kami_key, expire_time, max_uses, created_by, type, order_no) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt_kami->execute([
                $kami_key,
                $expire_time,
                0, // 无限制使用次数
                0, // 0 代表购买系统自动生成
                $product['name'],
                $order['order_no']
            ]);
            
            $kami_list[] = $kami_key;
        }
        
        // 更新订单的卡密信息
        $kami_text = implode("\n", $kami_list);
        writeDebugLog("准备更新订单的 kami_list: " . $kami_text);
        $stmt_order = $pdo->prepare("UPDATE orders SET kami_list = ? WHERE order_no = ?");
        $stmt_order->execute([$kami_text, $order['order_no']]);
        writeDebugLog("订单 kami_list 更新成功。");
        
        writeDebugLog("--- [SUCCESS] generateAndSendKami ---");
        return true;
        
    } catch (Exception $e) {
        writeDebugLog("[FATAL] generateAndSendKami 发生异常: " . $e->getMessage());
        return false;
    }
}
?> 